//
//  DownLoadManager.m
//  timeRadio
//
//  Created by shaneZhang on 14-3-15.
//  Copyright (c) 2014年 张毓庆. All rights reserved.
//

#import "DownLoadManager.h"
#import "AFDownloadRequestOperation.h"

#define DocumentsDirectory [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0]
@interface DownLoadManager()
@end
@implementation DownLoadManager
single_implementation(DownLoadManager)
- (void)beginDownload
{
    NSURL *url = [NSURL URLWithString:@"http://www.5288z.com/zip.zip"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:3600];
    
    AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:self.localPath shouldResume:YES];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"Successfully downloaded file to %@", self.localPath);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"downloadHasFinished" object:self];
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"Error: %@", error);
    }];
    
    [operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
        float percentDone = totalBytesReadForFile/(float)totalBytesExpectedToReadForFile;
        
        NSNumber *percent = [NSNumber numberWithFloat:percentDone];
        NSDictionary *dict = [NSDictionary dictionaryWithObject:percent forKey:@"percent"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"downing" object:self userInfo:dict];
        NSLog(@"------%f",percentDone);
        NSLog(@"Operation%i: bytesRead: %ld", 1, (long)bytesRead);
        NSLog(@"Operation%i: totalBytesRead: %lld", 1, totalBytesRead);
        NSLog(@"Operation%i: totalBytesExpected: %lld", 1, totalBytesExpected);
        NSLog(@"Operation%i: totalBytesReadForFile: %lld", 1, totalBytesReadForFile);
        NSLog(@"Operation%i: totalBytesExpectedToReadForFile: %lld", 1, totalBytesExpectedToReadForFile);
    }];
    [operation start];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
